//
//  TopBar.m
//  SinaNews
//
//  Created by hroot on 15/8/13.
//  Copyright (c) 2015年 Lily. All rights reserved.
//

#import "TopBar.h"
@interface TopBar()

@property (nonatomic,strong)UIView *markView;
@property (nonatomic,strong)NSMutableArray *buttons;

@end

@implementation TopBar

- (void)setTitles:(NSMutableArray *)titles{
    self.showsHorizontalScrollIndicator = NO;
    _titles = titles;
    self.buttons = [NSMutableArray array];
    CGFloat padding = 20.0;
    
    for (int i = 0; i < titles.count; i++) {
        if ([_titles[i] isKindOfClass:[NSNull class]]) {
            continue;
        }
        
        //buttons
        UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:_titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        //set button frame
        static CGFloat originX = 0;
        CGRect frame = CGRectMake(originX+padding, 0, button.intrinsicContentSize.width, kTopbarHeight);
        button.frame = frame;
        originX = CGRectGetMaxX(frame) + padding;//originX + padding + button.intrinsicContentSize.width;
        [self addSubview:button];
        [self.buttons addObject:button];
        
    }
    self.contentSize = CGSizeMake(CGRectGetMaxX([self.buttons.lastObject frame]), self.frame.size.height);
    
    //mark view
    UIButton *firstButton = self.buttons.firstObject;
    CGRect frame = firstButton.frame;
    self.markView = [[UIView alloc]initWithFrame:CGRectMake(frame.origin.x, CGRectGetMaxY(frame)-3, frame.size.width, 3)];
    _markView.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:_markView];
}

- (void)btnClick:(id)sender{
    self.currentPage = [self.buttons indexOfObject:sender];
    if (_blockHandler) {
        _blockHandler(_currentPage);
    }
}
- (void)setCurrentPage:(NSInteger)currentPage{
    _currentPage = currentPage;
    UIButton *button = [_buttons objectAtIndex:_currentPage];
    CGRect frame = button.frame;
    frame.origin.x -= 5;
    frame.size.width += 10;
    [self scrollRectToVisible:frame animated:YES];
    
    [UIView animateWithDuration:0.25f animations:^{
        self.markView.frame = CGRectMake(button.frame.origin.x, CGRectGetMaxY(button.frame)-3, button.frame.size.width, 3);
    } completion:nil];
}


@end
